import { Card, APIResponse, ServerInfo } from '../types/Card';
import { LOG_CONFIG } from '../config/api';
import { NativeModules } from 'react-native';

export class APIService {
  private static instance: APIService;
  private baseURL: string | null = null;
  private currentServer: ServerInfo | null = null;
  
  // 添加缓存机制
  private cache: Map<string, { data: any; timestamp: number }> = new Map();
  private CACHE_DURATION = 30000; // 30秒缓存

  private constructor() {}

  public static getInstance(): APIService {
    if (!APIService.instance) {
      APIService.instance = new APIService();
    }
    return APIService.instance;
  }

  /**
   * 设置服务器信息
   */
  public setServer(server: ServerInfo): void {
    this.currentServer = server;
    this.baseURL = server.url;
    console.log('✅ API 服务设置服务器:', server);
  }

  /**
   * 获取当前服务器信息
   */
  public getCurrentServer(): ServerInfo | null {
    return this.currentServer;
  }

  /**
   * 检查是否有可用的服务器
   */
  public hasServer(): boolean {
    return this.baseURL !== null;
  }

  /**
   * 检查缓存是否有效
   */
  private isCacheValid(key: string): boolean {
    const cached = this.cache.get(key);
    if (!cached) return false;
    
    const now = Date.now();
    return (now - cached.timestamp) < this.CACHE_DURATION;
  }

  /**
   * 清理过期缓存
   */
  private cleanExpiredCache(): void {
    const now = Date.now();
    for (const [key, value] of this.cache.entries()) {
      if ((now - value.timestamp) >= this.CACHE_DURATION) {
        this.cache.delete(key);
      }
    }
  }

  /**
   * 设置基础 URL（兼容旧版本）
   */
  public setBaseURL(url: string) {
    this.baseURL = url;
    this.currentServer = null;
  }

  private async request<T>(endpoint: string, options?: RequestInit): Promise<T> {
    if (!this.baseURL) {
      throw new Error('未设置 API 服务器，请先扫描网络或手动设置服务器地址');
    }

    const url = `${this.baseURL}${endpoint}`;
    const cacheKey = `${url}_${options?.method || 'GET'}`;
    
    // 清理过期缓存
    this.cleanExpiredCache();
    
    // 检查缓存
    if (this.isCacheValid(cacheKey)) {
      if (LOG_CONFIG.LOG_API_REQUESTS) {
        console.log('📦 使用缓存数据:', url);
      }
      return this.cache.get(cacheKey)!.data;
    }
    
    if (LOG_CONFIG.LOG_API_REQUESTS) {
      console.log('🌐 API 请求:', url);
    }
    
    try {
      const response = await fetch(url, {
        method: options?.method || 'GET',
        headers: {
          'Content-Type': 'application/json',
          ...options?.headers,
        },
        body: options?.body,
      });
      
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }

      const data = await response.json();
      
      // 缓存响应数据（仅对GET请求）
      if ((options?.method || 'GET') === 'GET') {
        this.cache.set(cacheKey, { data, timestamp: Date.now() });
      }
      
      return data;
    } catch (error) {
      console.error('API request failed:', error);
      throw error;
    }
  }

  public async getCards(): Promise<Card[]> {
    if (!this.baseURL) {
      throw new Error('未设置 API 服务器');
    }

    try {
      const { ApiModule } = NativeModules;
      const response = await ApiModule.getCards(this.baseURL);
      
      if (response.status >= 200 && response.status < 300) {
        const data = JSON.parse(response.body);
        if (data.code === 0) {
          return data.data;
        } else {
          throw new Error('API 返回错误: ' + data.message);
        }
      } else {
        throw new Error(`HTTP error! status: ${response.status}`);
      }
    } catch (error) {
      console.error('Native API request failed:', error);
      throw error;
    }
  }

  public async getCard(id: number): Promise<Card> {
    const response: APIResponse<Card> = await this.request(`/api/cards/${id}`);
    if (response.code === 0) {
      return response.data;
    } else {
      throw new Error('Failed to get card');
    }
  }

  public async syncStatus(deviceId: string): Promise<any> {
    const response: APIResponse<any> = await this.request(`/api/sync?device_id=${deviceId}`);
    if (response.code === 0) {
      return response.data;
    } else {
      throw new Error('Failed to sync status');
    }
  }

  public async healthCheck(): Promise<any> {
    if (!this.baseURL) {
      throw new Error('未设置 API 服务器');
    }

    try {
      const { ApiModule } = NativeModules;
      const response = await ApiModule.healthCheck(this.baseURL);
      
      if (response.status >= 200 && response.status < 300) {
        return JSON.parse(response.body);
      } else {
        throw new Error(`HTTP error! status: ${response.status}`);
      }
    } catch (error) {
      console.error('Native health check failed:', error);
      throw error;
    }
  }
}

export default APIService.getInstance(); 